<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;


use app\models\CrmHwzx;
use app\models\CrmHwzxHistory;
use app\models\CrmHwzxHistoryDg;
use app\models\CrmHwzxHistoryGd;
use app\models\CrmHwzxHistoryGt;
use app\models\CrmHwzxHistoryKhfp;
use app\models\CrmHwzxZccl;
use app\models\CrmMallOrder;
use app\models\CrmMallOrderDetail;
use app\models\CrmMallProduct;
use app\models\search\CrmHwzxSearch;
use common\helps\Tools;
use yii\helpers\ArrayHelper;

class CrmHotCenterHwzxController extends CommonController
{
    public $result = "";
    //查询来电号码
    public function actionFindLdhm(){
        $ldhm = is_set($_POST['CrmHwzxSearch'],'ldhm');
        $id = is_set($_POST['CrmHwzxSearch'],'id');
        //电话号码归属地
        $gsd = json_decode($this->actionPosts($ldhm),true);
        if (count($gsd)>0){
            $detail = $gsd[$ldhm]['detail'];
        }else{
            $detail = "";
        }
        if (!empty($id)){
            $model = CrmHwzxZccl::findOne(['id'=>$id]);
            if (empty($model)){
                $model = new CrmHwzxZccl();
            }
        }else{
            if (!empty($ldhm)){
                $model = CrmHwzx::findOne(['ldhm'=>$ldhm]);
                if (empty($model)){
                    $model = new CrmHwzx();
                }
            }
        }
        if (!empty($detail)){
            $model->hmgsd = (isset($detail['province'])?$detail['province']:"").'/'.(isset($detail['area']['0']['city'])?$detail['area']['0']['city']:"");//城市信息
        }else{
            $model->ldhm = $ldhm;
        }
        $models = ArrayHelper::toArray($model);
        if($models){
            $data = $models;
            $err = 1;
        }else{
            $errs = $model->getErrors();
            $errArr = [];
            foreach ($errs as $k=>$v){
                $errArr[] = $v[0];
            }
            $data = $errArr;
            $err = 0;
        }
        $res['data'] = $data;
        $res['phone'] = $data;
        $res['res'] = $err;
        return json_encode($res);
    }

    //查询列表 客户列表
    public function actionList(){
        $res = $this->getList(new CrmHwzx(),$_POST['page'],$_POST['limit'],['gsid'=>\Yii::$app->user->id]);
        return $res;
    }

    //查询列表 客户列表
    public function actionSearchList(){
        $search = new CrmHwzxSearch();
        $post = \Yii::$app->request->post();
        $res = $search->search($post);
        $count = $res->count;
        $res->query->limit($post['limit']);
        $res->query->offset($post['limit']*($post['page']-1));
        $final = $res->query->asArray()->all();
        return $this->actionLayData($count,ArrayHelper::toArray($final));
    }

    //查询 历史沟通记录
    public function actionFindLsgtjl(){//查询
        $ldhm = is_set($_POST,'ldhm');
        $other_id = is_set($_POST,'other_id');
        if (!empty($ldhm) || !empty($other_id)){
            empty($ldhm)?"":($condition['ldhm']=$ldhm);
            empty($other_id)?"":($condition['other_id']=$other_id);
            $res = $this->getList(new CrmHwzxHistoryGt(),$_POST['page'],$_POST['limit'],$condition);
            return $res;
        }else{
            return $this->actionNullLayData();
        }
    }
    //查询 历史订购记录
    public function actionFindLsdgjl(){//查询
        if (isset($_POST['ldhm'])){
            $ldhm = $_POST['ldhm'];
            $dg = new CrmHwzxHistoryGt();
            $all = $dg
                ->find()
                ->select("d.ldhm,o.*")
                ->from('crm_hwzx_history_gt as d')
                ->andWhere(['d.ldhm'=>$ldhm])
                ->andWhere(['d.cllx'=>'下订单'])
                ->leftJoin('crm_mall_order as o','o.id=d.order_id')
                ->asArray()
                ->all();
            return $this->actionLayData(count($all),$all);
        }else{
            return $this->actionNullLayData_();
        }
    }
    //查询 历史订购记录 商品
    public function actionFindLsdgjlSp(){//查询
        $product = new CrmMallOrderDetail();
        $all = $product->find()
            ->where(['order_id'=>$_POST['order_id']])
            ->asArray()
            ->all();
        return $this->actionLayData(count($all),$all);
    }

    public function actionBc(){//保存数据
        $this->startT();//开启事务
        $save = $this->actionSaveHwzx();
        $res = json_decode($save,true);
        $params = "";
        if ($res['res'] == 1){
            $other_id = is_set($_POST['params'],'other')."=".is_set($res['data'],'id');
            switch ($_POST['lsjlyddClick']){
                case "lsjl"://历史记录，
                    $params = ['cllx'=>'历史记录'];
                    break;
                case "wcjyy"://点击了未成交
                    $params = ['cllx'=>'未成交','khbz2'=>$_POST['wcjyy']];
                    break;
                case "xdd"://点击下订单
                    $order= json_decode($this->actionSaveOrder(),true);
                    if ($order['res']==0){//  保存订单成功
                        return json_encode($order);
                    }
                    $params = ['cllx'=>'下订单','order_id'=>$order['data']];
                    break;
                case "wxyy"://无效
                    $params = ['cllx'=>'无效','khbz2'=>$_POST['wxyy']];
                    break;
            }
            $params['other_id'] = $other_id;
            //保存历史记录
            if ($this->actionSaveHistoryGt(1,$params)){
                $this->transaction->commit();
                return $this->dealData("保存成功");
            }else{
                return $this->dealData("保存失败！",0);
            }
        }else{
            return $save;
        }
    }
    public function actionZc(){//暂存处理
        $this->transaction = \Yii::$app->getDb()->beginTransaction();//开启事务
        $save = $this->actionSaveHwzx();
        $res = json_decode($save,true);
        if ($res['res'] == 1){//保存成功，开始暂存
            $model = new CrmHwzxZccl();
            $array_zccl['CrmHwzxZccl'] = $_POST['khxx_data'];
            $array_zccl['CrmHwzxZccl']['ldzcsj'] = "".time();
            $array_zccl['CrmHwzxZccl']['id'] = "";
            $array_zccl['CrmHwzxZccl']['gsid'] = \Yii::$app->user->id;
            if ($model->load($array_zccl) && $model->save()){//  暂存 成功
                $params = "";
                $other_id = is_set($_POST['params'],'other')."=".$model->id;
                switch ($_POST['lsjlyddClick']){
                    case "lsjl"://历史记录，
                        $params = ['cllx'=>'历史记录'];
                        break;
                    case "wcjyy"://点击了未成交
                        $params = ['cllx'=>'未成交','khbz2'=>$_POST['wcjyy']];
                        break;
                    case "xdd"://点击下订单
                        $order= json_decode($this->actionSaveOrder(),true);
                        if ($order['res']==0){//  保存订单成功
                            return $this->dealData("保存失败！",0);
                        }
                        $params = ['cllx'=>'下订单','order_id'=>$order['data']];
                        break;
                    case "wxyy"://无效
                        $params = ['cllx'=>'无效','khbz2'=>$_POST['wxyy']];
                        break;
                }
                $params['other_id'] = $other_id;
                if ($this->actionSaveHistoryGt(2,$params)){
                    $this->transaction->commit();
                    return $this->dealData("保存成功");
                }else{
                    return $this->dealData("保存失败！",0);
                }
            }else{
                return $this->dealData($model->getErrors(),0);
            }
        }else{
            return $save;
        }
    }

    /**
     * 保存历史记录
     * state 是状态 1 是保存 2 是暂存
     * @return string
     */
    public function actionSaveHistoryGt($state,$params=""){//暂存处理
        $model = new CrmHwzxHistoryGt();
        $model->wcjyy = is_set($_POST,'wcjyy');
        $model->wxyy = is_set($_POST,'wxyy');
        $model->ldhm = is_set($_POST['khxx_data'],'ldhm');
        $model->gtsj = "" . time();
        $model->gh = "";
        $model->gsid = \Yii::$app->user->getId();
        $model->gtnr = is_set($_POST['khxx_data'],'gtnr');
        $model->zxcp = is_set($_POST['khxx_data'],'zxcp');
        $model->jcx = "1";
        $model->khbz = is_set($_POST['khxx_data'],'khbz');
        if (is_array($params)){
            foreach ($params as $k=>$v){
                $model->$k = $v;
            }
        }
        $model->khbz = is_set($_POST['khxx_data'],'khbz');
        if ($state==1){//保存
            $model->lx = "保存";
        }
        if ($state==2){//暂存
            $model->lx = "暂存";
        }
        if ($model->save()) {//  暂存 成功
            return $this->dealData("保存成功");
        } else {
            return $this->dealData($model->getErrors(),0);
        }
    }

    /**
     * 保存订单数据
     * @return string
     */
    public function actionSaveOrder(){
        $model = new CrmMallOrder();
        $data['CrmMallOrder'] = $_POST['order'];
        $data['CrmMallOrder']['xdsj'] = "".time();//下单时间
        $data['CrmMallOrder']['gsid'] = \Yii::$app->user->getId();//下单人员
        $data['CrmMallOrder']['ddbh'] = $this->gTestDdbhUnique($model);//产生订单唯一编号
        if ($model->load($data) && $model->save()) {//  保存订单
            //保存订单明细
            $selectedProduct = json_decode($_POST['selectedProduct'],true);
            foreach($selectedProduct as $k=>$v){
                if ($v!=[]){
                    $orderDetailModel = new CrmMallOrderDetail();
                    $datas['CrmMallOrderDetail'] = $v;
                    $datas['CrmMallOrderDetail']['product_id'] = $v['id'];
                    $datas['CrmMallOrderDetail']['order_id'] = $model->id;
                    if(!$orderDetailModel->load($datas) || !$orderDetailModel->save()){
                        return $this->dealData($orderDetailModel->getErrors(),0);
                    }
                }
            };
            return $this->dealData($model->id);
        } else {
            return $this->dealData($model->getErrors(),0);
        }
    }

    /**
     * 产生并测试订单编号唯一性
     */
    public function gTestDdbhUnique($model){
        $ddbh = generalUniqueId();
        //检验订单编号是否存在，存在就重新产生
        $count = $model->find()->where(['ddbh'=>$ddbh])->count();
        if ($count>0){
            $this->gTestDdbhUnique($model);
        }else{
            return $ddbh;
        }
    }

    /**
     * 将数据处理为自己需要的格式，前端需要相应的格式，统一的格式
     * @param $data
     * @return string
     */
    public function dealData($data,$state=1){
        if (!is_array($data) || $state==1){//  暂存 成功
            $data = $data;
            $code = $state;
        }else{
            $err = $data;
            $errArr = [];
            foreach ($err as $k=>$v){
                $errArr[] = $v[0];
            }
            $data = $errArr;
            $code = 0;
        }
        if ($state==0 && !empty($this->transaction)){
            $this->transaction->rollBack();//出错了，就回滚
        }
        $res['data'] = $data;
        $res['res'] = $code;
        return json_encode($res);
    }

    public function actionSaveHwzx(){//保存处理
        if (isset($_POST['params']['ldhm'])){
            $_POST['khxx_data']['ldhm'] = is_set($_POST['params'],'ldhm');
            $_POST['khxx_data']['mtly'] = is_set($_POST['params'],'mtly');
            $_POST['khxx_data']['bjhm'] = is_set($_POST['params'],'bjhm');
            $_POST['khxx_data']['zryy'] = is_set($_POST['params'],'zryy');
            $_POST['khxx_data']['zxcp'] = is_set($_POST['params'],'zxcp');
            $_POST['khxx_data']['gtnr'] = is_set($_POST['params'],'gtnr');
            $_POST['khxx_data']['gsid'] = \Yii::$app->getUser()->id;//归属id
            $_POST['khxx_data']['gxsj'] = "" . time();
            switch ($_POST['lsjlyddClick']){
                case "wcjyy"://点击了未成交
                    $_POST['khxx_data']['wcj'] = 1;
                    break;
                case "wxyy"://无效
                    $_POST['khxx_data']['wcj'] = 2;
                    break;
                case "xdd"://无效
                    $_POST['khxx_data']['wcj'] = 3;
                    break;
            }
            $array['CrmHwzx']=$_POST['khxx_data'];
            $model = new CrmHwzx();
            if (!empty($_POST['khxx_data']['id'])){//非空，为修改
                $model = CrmHwzx::findOne(['ldhm'=>$_POST['khxx_data']['ldhm']]);
                $arr['CrmHwzx'] = $_POST['khxx_data'];
                $this->saveHwzxHistory($arr,'修改');
                if ($model->load($arr) && $model->update()){//  客户信息更新成功 同时暂存 处理也要保存一条记录
                    //如果是来自暂存的数据 ，就删除暂存的那条数据
                    if (isset($_POST['khxx_data']['ldzcsj'])){//表示是暂存的
                        $modelZc = CrmHwzxZccl::findOne($_POST['khxx_data']['id']);
                        if (!$modelZc->delete()){//删除暂存的那条数据记录
                            $this->dealData($modelZc->getErrors(),0);
                        }
                    }
                    return $this->dealData($model->attributes);
                }else{
                    return $this->dealData($model->getErrors(),0);
                }
            }else{
                $this->saveHwzxHistory($array,'新增');
                if ($model->load($array) && $model->save()){//  客户信息保存成功 同时暂存 处理也要保存一条记录
                    return $this->dealData($model->attributes);
                }else{
                    return $this->dealData($model->getErrors(),0);
                }
            }
        }else{
            return $this->dealData("电话号码为空",0);
        }
    }

    /**
     * 保存话务中心的操作历史记录
     * @param $arr
     * @return int
     */
    public function saveHwzxHistory($arr,$c){
        $history = new CrmHwzxHistory();
        $history->operatorUserid = $_COOKIE['gsid'];
        $history->operatorUsername  = $_COOKIE['user'];
        $history->operatorYggh  = $_COOKIE['yggh'];
        $history->operatorRIp  = Tools::ip();
        $history->operatorLIp  = $_COOKIE['ip'];
        $history->operatorZuoxi  = $_COOKIE['zuoxi'];
        $history->operatorContent  = $c;
        $history->gnk = '话务中心';
        if($history->load($arr,'CrmHwzx') && $history->save()){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 查询电话号码归属地
     * 传过来 phone
     * @return string
     */
    public function actionPosts($phone){
        header('Content-type:text/html; charset="utf-8"');
        $host = "https://mobsec-dianhua.baidu.com";
        $path = "/dianhua_api/open/location";
        $method = "GET";
        $appcode = "1c97d9e8fe17410987052c6ced218189";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "tel=" . $phone;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $content = curl_exec($curl);
        $header_size = curl_getinfo($curl,CURLINFO_HEADER_SIZE);
        $bodys = substr($content,$header_size);
        $res = json_decode($bodys,true);
        if($res['responseHeader']['status']==200){
            //说明查询成功
            $data = $res['response'];
        }else{
            $data = array(
                'status'=>0,
                'msg'=>$res['msg'],
                'data'=>'',
            );

        }
        return json_encode($data);
    }
}